﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using System.IO;
using RenderHeads.Media.AVProVideo;
using DG.Tweening;
using System.Text;

[AddComponentMenu(menuName:"Video Controller/VideoController")]
public class VideoController : MonoBehaviour
{
    public GameObject ContentParentNode;

    /// <summary>
    /// index-----0:Text, 1:Button, 2:Image, 3:Line(image)-----index
    /// </summary>
    public GameObject[] ItemChildObjects;
    public GameObject EmptyContentInfo;

    public MediaPlayer MediaPlayerComponent;
    public GameObject MediaPlayerUI;

    /// <summary>
    /// 应用程序当前版本
    /// </summary>
    public static float AppCurrentVerson
    {
        get => PlayerPrefs.GetFloat("AppCurrentVerson", 0.99F);
        set => PlayerPrefs.SetFloat("AppCurrentVerson", value);
    }
    public static float networkVerson;

    // Start is called before the first frame update
    void Awake()
    {
        StartCoroutine(GetTxt("https://maxshadow-1305646487.cos.ap-beijing.myqcloud.com/Txt/Version.txt", NetworkTxtType.Verson));
    }

    /// <summary>
    /// 获取网络资源
    /// </summary>
    /// <param name="url">网络资源链接</param>
    /// <param name="type">网络资源链接文本的类型</param>
    /// <returns></returns>
    private IEnumerator GetTxt(string url, NetworkTxtType type)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();

        if (request.downloadHandler.isDone) //加载完成
        {
            switch (type)
            {
                case NetworkTxtType.MainInfo:
                    if (Application.platform == RuntimePlatform.WindowsEditor ||
                        Application.platform == RuntimePlatform.WindowsPlayer) File.WriteAllText(Application.streamingAssetsPath + "/MainInfo.txt", request.downloadHandler.text);
                    else if (Application.platform == RuntimePlatform.Android) File.WriteAllText(Application.persistentDataPath + "/MainInfo.txt", request.downloadHandler.text);

                    if (SceneManager.GetActiveScene().name == "Loading") break;
                    string[] mainInfoEveryGroup = request.downloadHandler.text.Split('@');
                    StartCoroutine(InstantiateAllContent(mainInfoEveryGroup));
                    break;
                case NetworkTxtType.Verson:
                    string[] networkVersonString = request.downloadHandler.text.Split('=');
                    networkVerson = float.Parse(networkVersonString[1]);
                    if (networkVerson == AppCurrentVerson) //直接加载本地的一下MainInfo资源，这样就节省了再次从云对象存储平台获取资源
                    {
                        if (SceneManager.GetActiveScene().name != "Loading")
                        {
                            if (Application.platform == RuntimePlatform.WindowsEditor ||
                        Application.platform == RuntimePlatform.WindowsPlayer)
                            {
                                string[] mainInfoEveryGroup_2 = File.ReadAllText(Application.streamingAssetsPath + "/MainInfo.txt").Split('@');
                                StartCoroutine(InstantiateAllContent(mainInfoEveryGroup_2));
                            }
                            else if (Application.platform == RuntimePlatform.Android)
                            {
                                string[] mainInfoEveryGroup_2 = File.ReadAllText(Application.persistentDataPath + "/MainInfo.txt").Split('@');
                                StartCoroutine(InstantiateAllContent(mainInfoEveryGroup_2));
                            }
                        }
                        StartCoroutine(ReadUserInfo(false));
                    }
                    else //最新的网络版本不等于当前的版本，获取MainInfo.txt并且存到本地
                    {
                        ShareManager.canUpdateShareContent = true;
                        StartCoroutine(GetTxt("https://maxshadow-1305646487.cos.ap-beijing.myqcloud.com/Txt/MainInfo.txt", NetworkTxtType.MainInfo));

                        StartCoroutine(ReadUserInfo(true));
                    }
                    break;
            }
        }
        else if (request.error != null) //加载出错
        {
            Debug.LogError("获取远程资源出错");
            AndroidJavaObject javaObject = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
            javaObject.Call<bool>("showToast", "网络连接失败");
        }
    }

    private IEnumerator ReadUserInfo(bool getNetworkInfo)
    {
        if (getNetworkInfo)
        {
            UnityWebRequest request_2 = UnityWebRequest.Get("https://maxshadow-1305646487.cos.ap-beijing.myqcloud.com/Txt/UserInfo.txt");
            yield return request_2.SendWebRequest();

            if (request_2.isDone)
            {
                if (Application.platform == RuntimePlatform.WindowsEditor ||
                        Application.platform == RuntimePlatform.WindowsPlayer)
                    File.WriteAllText(Application.streamingAssetsPath + "/UserInfo.txt", request_2.downloadHandler.text);
                else if (Application.platform == RuntimePlatform.Android)
                    File.WriteAllText(Application.persistentDataPath + "/UserInfo.txt", request_2.downloadHandler.text);
            }

            string[] userInfos = request_2.downloadHandler.text.Split('\n');
            UpdateUserInfo(userInfos);
        }
        else
        {
            string[] userInfos = null;
            if (Application.platform == RuntimePlatform.WindowsEditor ||
                    Application.platform == RuntimePlatform.WindowsPlayer)
                userInfos = File.ReadAllText(Application.streamingAssetsPath + "/UserInfo.txt").Split('\n');
            else if (Application.platform == RuntimePlatform.Android)
                userInfos = File.ReadAllText(Application.persistentDataPath + "/UserInfo.txt").Split('\n');
            UpdateUserInfo(userInfos);
        }
    }

    private void UpdateUserInfo(string[] infos)
    {
        foreach (string item in infos)
        {
            string[] oneLine = item.Split('=');
            switch (oneLine[0])
            {
                case "HeadPictureLink":
                    if (networkVerson != AppCurrentVerson)
                    {
                        StartCoroutine(GetImage(oneLine[1], null));
                        AppCurrentVerson = networkVerson;
                    }
                    else
                    {
                        SetHeadPictureComponent();
                    }
                    break;
                case "UserName":
                    foreach (GameObject userName in GameObject.FindGameObjectsWithTag("UserName"))
                    {
                        userName.GetComponent<Text>().text = oneLine[1];
                    }
                    break;
                case "TelePhoneNumber":
                    foreach (GameObject number in GameObject.FindGameObjectsWithTag("TelePhoneNumber"))
                    {
                        number.GetComponent<Text>().text = $"电话：{oneLine[1]}";
                    }
                    break;
            }
        }
    }

    private void SetHeadPictureComponent()
    {
        Texture2D texture = new Texture2D(1, 1);

        if (Application.platform == RuntimePlatform.WindowsEditor ||
        Application.platform == RuntimePlatform.WindowsPlayer)
            texture.LoadImage(File.ReadAllBytes(Application.streamingAssetsPath + "/HeadPicture.png"));
        else if (Application.platform == RuntimePlatform.Android)
            texture.LoadImage(File.ReadAllBytes(Application.persistentDataPath + "/HeadPicture.png"));

        texture.Apply();

        foreach (GameObject picture in GameObject.FindGameObjectsWithTag("HeadPicture"))
        {
            picture.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        }
    }

    private IEnumerator GetImage(string url, Image fileImage)
    {
        UnityWebRequest WebRequest = new UnityWebRequest(url);
        DownloadHandlerTexture Download = new DownloadHandlerTexture();
        WebRequest.downloadHandler = Download;
        yield return WebRequest.SendWebRequest();

        if (WebRequest.downloadHandler.isDone)
        {
            if (!fileImage)
            {
                if (Application.platform == RuntimePlatform.WindowsEditor ||
                    Application.platform == RuntimePlatform.WindowsPlayer)
                    File.WriteAllBytes(Application.streamingAssetsPath + "/HeadPicture.png", Download.data);
                else if (Application.platform == RuntimePlatform.Android)
                    File.WriteAllBytes(Application.persistentDataPath + "/HeadPicture.png", Download.data);

                SetHeadPictureComponent();
            }
            else
            {
                Rect spriteRect = new Rect(0, 0, Download.texture.width, Download.texture.height);
                Sprite sprite = Sprite.Create(Download.texture, spriteRect, Vector2.zero);
                fileImage.sprite = sprite;
            }
        }
    }


    //获取最真实字符串长度
    private static int GetStrLength(string str)
    {
        if (string.IsNullOrEmpty(str)) return 0;
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        byte[] s = ascii.GetBytes(str);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
        }
        //Debug.Log("当前字符串长度为：" + tempLen);
        return tempLen;
    }

    /// <summary>
    /// 通过网络实例化所有内容
    /// </summary>
    /// <param name="mainInfoEveryGroup">每组主要信息</param>
    private IEnumerator InstantiateAllContent(string[] mainInfoEveryGroup)
    {
        EmptyContentInfo.SetActive(true);
        foreach (string group in mainInfoEveryGroup)
        {
            EmptyContentInfo.SetActive(false);
            string[] mainInfoEveryRow = group.Split('\n');
            GameObject node = Instantiate(ContentParentNode, GameObject.Find("MainPanel/Panel/Scroll View/Viewport/Content").transform);
            foreach (string item in mainInfoEveryRow)
            {
                string[] mainInfoOneRow = item.Split('=');
                switch (mainInfoOneRow[0])
                {
                    case "Text":
                        Text contentText = Instantiate(ItemChildObjects[0], node.transform).GetComponent<Text>();
                        contentText.text = mainInfoOneRow[1];
                        if (GetStrLength(contentText.text) > 40)
                        {
                            AutoSetItemHeight(node.GetComponent<RectTransform>(), 50F + 97.12949F);
                            Vector2 vector2 = contentText.GetComponent<RectTransform>().sizeDelta;
                            contentText.GetComponent<RectTransform>().sizeDelta = new Vector2(vector2.x, 97.12949F);
                        }
                        else
                        {
                            AutoSetItemHeight(node.GetComponent<RectTransform>(), 50F + 48.564745F);
                            Vector2 vector2 = contentText.GetComponent<RectTransform>().sizeDelta;
                            contentText.GetComponent<RectTransform>().sizeDelta = new Vector2(vector2.x, 48.564745F);
                        }

                        AppUIManager.instance.videoTexts.Add(contentText);
                        if (GetStrLength(contentText.text) > 80)
                            contentText.transform.Find("More_Btn").gameObject.SetActive(true);
                        else
                            contentText.transform.Find("More_Btn").gameObject.SetActive(false);
                        break;
                    case "Link":
                        VideoComponentExtend video_2 = Instantiate(ItemChildObjects[1], node.transform).GetComponent<VideoComponentExtend>();
                        AutoSetItemHeight(node.GetComponent<RectTransform>(), 50F + 500F);

                        video_2.VideoLink = mainInfoOneRow[1];
                        video_2.MediaPlayerComponent = MediaPlayerComponent;
                        video_2.MediaPlayerUI = MediaPlayerUI;
                        break;
                    case "Image":
                        Image imageObject = Instantiate(ItemChildObjects[2], node.transform).transform.GetChild(0).GetComponent<Image>();
                        AutoSetItemHeight(node.GetComponent<RectTransform>(), 50F + 550F);
                        StartCoroutine(GetImage(mainInfoOneRow[1], imageObject));
                        break;
                }
            }
            Instantiate(ItemChildObjects[3], node.transform);
            AutoSetItemHeight(node.GetComponent<RectTransform>(), 50F + 30F);


            foreach (Image item in node.GetComponentsInChildren<Image>())
            {
                Color color = item.color;
                item.color = new Color(color.r, color.g, color.b, 0.25F);
                item.DOFade(1F, 0.8F);
            }


            yield return new WaitForSeconds(0.2F);
        }

        //通知视频内容者处理视频内容大小
        //AutomaticallyArrangeContent.UpdateContentPanelSize += VideoContentSizePressed;
    }

    private void AutoSetItemHeight(RectTransform rectTransform, float addHeight) => rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, rectTransform.sizeDelta.y + addHeight);

    private void VideoContentSizePressed()
    {
        //this is null
    }

    enum NetworkTxtType
    {
        MainInfo,
        Verson
    }
}